#!/bin/bash

# Copyright (c) KylinSoft Co., Ltd. 2016-2024.All rights reserved.
## kylin-kmre-make-image is licensed under the Apache License, Version 2.0.
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##         http://www.apache.org/licenses/LICENSE-2.0
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.

ARCH=$(uname --processor)

destpath=$(pwd)
echo "$USER"
if [ "$USER" != "root" ]; then
    echo "你需要执行su - 后再执行！"
    exit 0
fi

[ -f "system.sfs" ] && rm -f "system.sfs"

# 第一步：复制system.sfs到目标机器上
IMAGE_DIR=$HOME
if [ "$SUDO_USER" != "" ]; then
    if [ "$SUDO_USER" != "root" ]; then
        IMAGE_DIR=/home/$SUDO_USER
    fi
fi

if [ "$IMAGE_DIR_PREFIX" != "" ]; then
    IMAGE_DIR=$IMAGE_DIR_PREFIX
fi

rm ${destpath}/system.sfs
ln -sf $IMAGE_DIR/system.sfs ${destpath}/system.sfs

# 检查镜像是否复制成功
if [ ! -f "${destpath}/system.sfs" ]; then
    echo "${destpath}/system.sfs not exist"
    exit 0
fi

# 第二步：删除上次的缓存文件
rm -f kmre3_v3.0-*.tar
rm -rf kmre-filesystem

# 修改build-docker-image.sh里的版本号
declare update_val
line_num=`grep -n "DOCKER_IMAGE_VERSION"  build-docker-image.sh | head -1 | cut -d ":" -f 1`
line_con=`sed -n ${line_num}p build-docker-image.sh`
old_val=${line_con: 0-9: 6}
cur_val=`date "+%y%m%d"`
set_val=$1
if [ -n "$set_val" ]; then
    update_val=v3.0-${set_val}
    sed -i "${line_num}c DOCKER_IMAGE_VERSION=v3.0-${set_val}" build-docker-image.sh
    echo "set designated val version"
    echo ${update_val}
elif [ "${old_val}" == "${cur_val}" ]; then
    echo "equals"
    ver_code=${line_con: 0-2: 2}
    declare -i new_ver=${ver_code}+1
    update_val=v3.0-${cur_val}.${new_ver}
    sed -i "${line_num}c DOCKER_IMAGE_VERSION=v3.0-${cur_val}.${new_ver}" build-docker-image.sh
    echo ${update_val}
else
    update_val=v3.0-${cur_val}.10
    sed -i "${line_num}c DOCKER_IMAGE_VERSION=v3.0-${cur_val}.10" build-docker-image.sh
    echo ${update_val}
fi

echo "exec build-docker-image.sh"
./build-docker-image.sh

# 修改kmre.conf的tag值
#/usr/share/kmre/kmre.conf
tag_num=`grep -n "tag="  /usr/share/kmre/kmre.conf | head -1 | cut -d ":" -f 1`
sed -i "${tag_num}c tag=${update_val}" /usr/share/kmre/kmre.conf
sync;sync

echo "copy kmre3_v1.0*.tar to /usr/share/kmre/"

cp kmre3_v3.0-*.tar /usr/share/kmre/kmre-container-image.tar
sync;sync

#reboot
echo "start load docker."
docker load -i /usr/share/kmre/kmre-container-image.tar
echo "Success!"
exit 0
